package com.whlilong.jxc.purcharsmanager.editor;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.tablecombo.TableCombo;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;
import com.whlilong.jxc.db.DbManager;
import com.whlilong.jxc.editor.support.InBaseCheckEdtiorSupport;
import com.whlilong.jxc.listener.IEditorListener;
import com.whlilong.jxc.model.Bookbill;
import com.whlilong.jxc.model.Goodsinfo;
import com.whlilong.jxc.model.Goodsreceiving;
import com.whlilong.jxc.model.Hsinfo;
import com.whlilong.jxc.model.Inbasebill;
import com.whlilong.jxc.model.Iostorage;
import com.whlilong.jxc.model.Purcharsbook;
import com.whlilong.jxc.model.Selldetail;
import com.whlilong.jxc.model.Storage;
import com.whlilong.jxc.model.Yginfo;
import com.whlilong.jxc.print.IconSource;
import com.whlilong.jxc.print.PDocument;
import com.whlilong.jxc.print.PHLine;
import com.whlilong.jxc.print.PTableBoxProvider;
import com.whlilong.jxc.print.PTextBox;
import com.whlilong.jxc.print.PVSpace;
import com.whlilong.jxc.print.PrintPreview;
import com.whlilong.jxc.print.SWTPTable;
import com.whlilong.jxc.sys.ExtentionInfo;
import com.whlilong.jxc.sys.SaveLogInfo;
import com.whlilong.jxc.sys.SetTableColColorListener;
import com.whlilong.jxc.ui.provider.CheckbillTableContentProvider;
import com.whlilong.jxc.ui.provider.CheckbillTableLableProvider;
import com.whlilong.jxc.ui.provider.CheckdetailTableContentProvider;
import com.whlilong.jxc.ui.provider.CheckdetailTableLableProvider;
import com.whlilong.jxc.ui.sorter.DistrictSorter;

/**
 * 入库验收单
 * @author auzn
 *
 */
public class InBaseCheckEditor extends AbstractEditor implements
		IEditorListener {
	private List<Goodsreceiving> detailList = new ArrayList<Goodsreceiving>();
	private Combo comboBase;
	private Combo comboPurcharsbook;
	private DateChooserCombo dateChooserCombo;
	private DateChooserCombo enabledateChooserCombo;
	private Text textUser;
	private Text textBase;
	private Text textInbaseId;
	private Text textBusinessName;
	private Text textAuditing;
	private Table table;
	private Combo comboPeople;
	private TableCombo tableComboBusinessid;
	private List<Hsinfo> businessList = new ArrayList<Hsinfo>();
	protected String businessname;
	private Composite container;
	private Label labelAuditingStatus;
	private Composite composite;
	private SashForm sashForm;
	private Composite composite_1;
	private Label labelCheckbill;
	private TableViewer billtableViewer;
	private Table billtable;
	private Label labelCheckdetail;
	private TableViewer detailtableViewer;
	private Table detailtable;
	private List<Inbasebill> billList = new ArrayList<Inbasebill>();
	protected List<Goodsinfo> goodsidList = new ArrayList<Goodsinfo>();
	protected int type = 1;// 1--直接入库;0--订单入库;
	protected int audited = 1;// 0--订货数量小于1，不能通过审核；1--初始状态 ；2--已审核状态 。
	private boolean isSave = false;
	protected int row = 0;
	protected StringBuffer rowBuffer = new StringBuffer();
	private CTabFolder tabFolder;
	private CTabItem tabItem;
	private CTabItem tabItem_1;

	public InBaseCheckEditor() {
	}

	/**
	 * @wbp.parser.entryPoint
	 */
	public Control createGroupText(Composite parent) {

		container = new Composite(parent, SWT.NONE);
		final GridLayout gl_container = new GridLayout(1, false);
		container.setLayout(gl_container);

		createBook(container);
		initial();
		setInput();
		addListener();
		return container;
	}

	private void createBook(Composite parent) {

		tabFolder = new CTabFolder(container, SWT.BORDER);
		tabFolder.setSimple(false);
		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));
		tabFolder.setSelectionBackground(Display.getCurrent().getSystemColor(
				SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT));

		tabItem = new CTabItem(tabFolder, SWT.NONE);
		tabItem.setImage(ResourceManager.getPluginImage("com.whlilong.jxc",
				"icons/brand1.gif"));
		tabItem.setText("单据录入");

		Composite compositeWrite = new Composite(tabFolder, SWT.NONE);
		tabItem.setControl(compositeWrite);
		compositeWrite.setLayout(new GridLayout(1, false));

		Composite compositeCheckbill = new Composite(compositeWrite, SWT.BORDER);
		compositeCheckbill.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				true, false, 1, 1));
		compositeCheckbill.setLayout(new GridLayout(7, false));

		labelAuditingStatus = new Label(compositeCheckbill, SWT.NONE);
		labelAuditingStatus.setFont(SWTResourceManager.getFont("华文彩云", 12,
				SWT.BOLD));
		labelAuditingStatus.setForeground(SWTResourceManager
				.getColor(SWT.COLOR_RED));
		labelAuditingStatus.setBounds(0, 0, 61, 17);
		labelAuditingStatus.setText("未审核");

		Label labelTitle = new Label(compositeCheckbill, SWT.NONE);
		labelTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 6, 1));
		labelTitle.setFont(SWTResourceManager.getFont("微软雅黑", 12, SWT.NORMAL));
		labelTitle.setForeground(Display.getDefault().getSystemColor(
				SWT.COLOR_DARK_GREEN));
		labelTitle.setAlignment(SWT.CENTER);
		labelTitle.setText("入库验收单");

		Label labelBusiness = new Label(compositeCheckbill, SWT.NONE);
		labelBusiness.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		labelBusiness.setText("供应商：");

		tableComboBusinessid = new TableCombo(compositeCheckbill, SWT.BORDER
				| SWT.READ_ONLY);
		tableComboBusinessid.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				true, false, 1, 1));
		tableComboBusinessid.setTableWidthPercentage(93);
		tableComboBusinessid
				.defineColumns(new String[] { "ID", "货商编号", "货商名称" });
		tableComboBusinessid.setDisplayColumnIndex(1);
		tableComboBusinessid.setShowTableHeader(true);
		businessList = ExtentionInfo.getInstance().getBusinessInfoList();
		loadThreeColumnDataset(tableComboBusinessid.getTable(), businessList);

		textBusinessName = new Text(compositeCheckbill, SWT.BORDER
				| SWT.READ_ONLY);
		textBusinessName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		textBusinessName.setEnabled(false);

		Label labelDate = new Label(compositeCheckbill, SWT.NONE);
		labelDate.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		labelDate.setText("日期：");

		dateChooserCombo = new DateChooserCombo(compositeCheckbill, SWT.BORDER
				| SWT.READ_ONLY);
		dateChooserCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				false, false, 1, 1));

		Label labelInbaseId = new Label(compositeCheckbill, SWT.NONE);
		labelInbaseId.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		labelInbaseId.setText("入库单号：");

		textInbaseId = new Text(compositeCheckbill, SWT.BORDER | SWT.READ_ONLY);
		textInbaseId.setEnabled(false);
		textInbaseId.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));

		Label labelBase = new Label(compositeCheckbill, SWT.NONE);
		labelBase.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		labelBase.setText("仓库：");

		comboBase = new Combo(compositeCheckbill, SWT.NONE);
		comboBase.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));

		textBase = new Text(compositeCheckbill, SWT.BORDER | SWT.READ_ONLY);
		textBase.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		textBase.setEnabled(false);

		Label labelPeople = new Label(compositeCheckbill, SWT.NONE);
		labelPeople.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		labelPeople.setText("经办人：");

		comboPeople = new Combo(compositeCheckbill, SWT.READ_ONLY);
		comboPeople.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		// 生成业务员信息
		comboPeople.add("未签名");
		List<Yginfo> staff = ExtentionInfo.getInstance().getStaffInfoList();
		for (int i = 0; i < staff.size(); i++) {
			comboPeople.add(staff.get(i).getYgname());
		}

		Label labelUser = new Label(compositeCheckbill, SWT.NONE);
		labelUser.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		labelUser.setText("操作员：");

		textUser = new Text(compositeCheckbill, SWT.BORDER | SWT.READ_ONLY);
		textUser.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));
		textUser.setEnabled(false);

		Label labelPurcharsbook = new Label(compositeCheckbill, SWT.NONE);
		labelPurcharsbook.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER,
				false, false, 1, 1));
		labelPurcharsbook.setText("订货单号：");

		comboPurcharsbook = new Combo(compositeCheckbill, SWT.READ_ONLY);
		comboPurcharsbook.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				true, false, 1, 1));
		new Label(compositeCheckbill, SWT.NONE);

		Label labelEnabledate = new Label(compositeCheckbill, SWT.NONE);
		labelEnabledate.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER,
				false, false, 1, 1));
		labelEnabledate.setText("有效日期：");

		enabledateChooserCombo = new DateChooserCombo(compositeCheckbill,
				SWT.BORDER | SWT.READ_ONLY);
		enabledateChooserCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				false, false, 1, 1));

		Label labelAudited = new Label(compositeCheckbill, SWT.NONE);
		labelAudited.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		labelAudited.setText("审核人：");

		textAuditing = new Text(compositeCheckbill, SWT.BORDER | SWT.READ_ONLY);
		textAuditing.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		textAuditing.setEnabled(false);

		createTableViewer(compositeWrite);

		tabItem_1 = new CTabItem(tabFolder, SWT.NONE);
		tabItem_1.setText("单据浏览");

		Composite compositeRead = new Composite(tabFolder, SWT.NONE);
		tabItem_1.setControl(compositeRead);
		compositeRead.setLayout(new GridLayout(1, false));

		sashForm = new SashForm(compositeRead, SWT.VERTICAL);
		sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));
		composite = new Composite(sashForm, SWT.BORDER);
		composite_1 = new Composite(sashForm, SWT.BORDER);
		sashForm.setWeights(new int[] { 1, 1 });
		createCheckbill(composite);
		createCheckdetail(composite_1);

		tabFolder.setSelection(tabItem);// 初始化选中对应的Item.
	}

	private void createTableViewer(Composite parent) {
		Composite compositeCheckdetail = new Composite(parent, SWT.BORDER);
		GridLayout gl = new GridLayout(4, false);
		gl.marginRight = 10;
		compositeCheckdetail.setLayout(gl);
		compositeCheckdetail.setLayoutData(new GridData(GridData.FILL_BOTH));

		tableViewer = new TableViewer(compositeCheckdetail, SWT.BORDER
				| SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.CHECK);
		tableViewer.setUseHashlookup(true);

		GridData gd = new GridData(GridData.FILL_BOTH);
		gd.horizontalSpan = 4;
		table = tableViewer.getTable();
		table.setLayoutData(gd);
		table.setToolTipText("点击单元格对数据进行修改！");
		// 设置行高
		table.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {

				event.height = 20;
			}
		});

		InBaseCheckEdtiorSupport editingSupport = new InBaseCheckEdtiorSupport(
				tableViewer, 1, this);
		createColumn("ID", DistrictSorter.ID_ASC, DistrictSorter.ID_DESC,
				editingSupport);

		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 2, this);
		createColumn("商品编号", DistrictSorter.ksid_asc, DistrictSorter.ksid_desc,
				editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 3, this);
		createColumn("商品条码", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 4, this);
		createColumn("商品名称", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 5, this);
		createColumn("单位", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 6, this);
		createColumn("数量", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 7, this);
		createColumn("原价", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 8, this);
		createColumn("折扣", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 9, this);
		createColumn("单价", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 10, this);
		createColumn("金额", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 11, this);
		createColumn("零售价", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 12, this);
		createColumn("零售金额", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 13, this);
		createColumn("生产日期", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 14, this);
		createColumn("失效日期", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new InBaseCheckEdtiorSupport(tableViewer, 14, this);
		createColumn("库位", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);

		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		// initial the tabelViewer
		tableViewer.setContentProvider(new CheckdetailTableContentProvider());
		tableViewer.setLabelProvider(new CheckdetailTableLableProvider());
		tableViewer.setInput(detailList);
		table.addListener(SWT.EraseItem, new SetTableColColorListener(table));

		table.select(0);
		table.setFocus();

		addTableListener();

	}

	private void createCheckbill(Composite parent) {

		parent.setLayout(new GridLayout(1, false));
		labelCheckbill = new Label(parent, SWT.NONE);
		labelCheckbill.setText("单据汇总表");

		billtableViewer = new TableViewer(parent, SWT.BORDER | SWT.H_SCROLL
				| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.CHECK);
		billtableViewer.setUseHashlookup(true);
		billtable = billtableViewer.getTable();
		billtable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));
		billtable.setToolTipText("点击单元格对数据进行修改！");
		// 设置行高
		billtable.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {

				event.height = 20;
			}
		});

		createColumn("ID", DistrictSorter.ID_ASC, DistrictSorter.ID_DESC,
				billtableViewer);
		createColumn("审核", DistrictSorter.ksid_asc, DistrictSorter.ksid_desc,
				billtableViewer);
		createColumn("业务类型", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("单据号", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("仓库名称", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("供应商编号", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("供应商名称", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("金额", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("经办人", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("订单号", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("操作员", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("日期", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("审核人", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);
		createColumn("限付日期", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, billtableViewer);

		billtable.setHeaderVisible(true);
		billtable.setLinesVisible(true);

		// initial the tabelViewer
		billtableViewer.setContentProvider(new CheckbillTableContentProvider());
		billtableViewer.setLabelProvider(new CheckbillTableLableProvider());

		billtable.addListener(SWT.EraseItem, new SetTableColColorListener(
				billtable));
		billtable.select(0);
		billtable.setFocus();
	}

	private void createCheckdetail(Composite parent) {
		parent.setLayout(new GridLayout(1, false));

		labelCheckdetail = new Label(parent, SWT.NONE);
		labelCheckdetail.setText("单据明细表");

		detailtableViewer = new TableViewer(parent, SWT.BORDER | SWT.H_SCROLL
				| SWT.FULL_SELECTION);
		detailtableViewer.setUseHashlookup(true);
		detailtable = detailtableViewer.getTable();
		detailtable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
				1, 1));
		detailtable.setToolTipText("点击单元格对数据进行修改！");
		// 设置行高
		detailtable.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {

				event.height = 20;
			}
		});

		createColumn("ID", DistrictSorter.ID_ASC, DistrictSorter.ID_DESC,
				detailtableViewer);
		createColumn("商品编号", DistrictSorter.ksid_asc, DistrictSorter.ksid_desc,
				detailtableViewer);
		createColumn("商品条码", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("商品名称", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("单位", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("数量", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("原价", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("折扣", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("单价", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("金额", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("零售价", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("零售金额", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("生产日期", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("失效日期", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);
		createColumn("库位", DistrictSorter.ksarea_asc,
				DistrictSorter.ksarea_desc, detailtableViewer);

		detailtable.setHeaderVisible(true);
		detailtable.setLinesVisible(true);

		// initial the tabelViewer
		detailtableViewer
				.setContentProvider(new CheckdetailTableContentProvider());
		detailtableViewer.setLabelProvider(new CheckdetailTableLableProvider());
		detailtable.addListener(SWT.EraseItem, new SetTableColColorListener(
				detailtable));
		detailtable.select(0);
		detailtable.setFocus();

	}

	private void initial() {
		labelAuditingStatus.setText("未审核");
		tableComboBusinessid.setText("0000");
		textBusinessName.setText("不定");
		dateChooserCombo.setValue(new Date());

		String checkid = "";
		int id = 1;
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		String date = df.format(new Date());
		long model = Long.parseLong(date) * 100000;
		billList = ExtentionInfo.getInstance().getInbaseinfo();
		if (billList.size() > 0)
			id = billList.get(billList.size() - 1).getId() + 1;
		model += id;
		checkid = String.valueOf(model);
		textInbaseId.setText(checkid);

		comboBase.setText("0000");
		textBase.setText("不定");
		comboPeople.select(0);
		textUser.setText(SaveLogInfo.getInstance().getUsername());
		List<Bookbill> bblist = ExtentionInfo.getInstance()
				.getPurcharsBookbill();
		comboPurcharsbook.add("不定");
		for (int i = 0; i < bblist.size(); i++) {
			comboPurcharsbook.add(bblist.get(i).getBookid());
		}
		comboPurcharsbook.select(0);
		Calendar c = Calendar.getInstance();// 两周的有效期，当前日期加上14天。。
		c.add(c.DATE, 14);
		enabledateChooserCombo.setValue(c.getTime());

		billList.clear();
		Inbasebill bb = new Inbasebill();
		bb.setStatus("0");
		bb.setAuditingid(SaveLogInfo.getInstance().getUsername());
		bb.setInbaseno(textInbaseId.getText());
		bb.setBaseid(comboBase.getText());
		bb.setBookid(comboPurcharsbook.getText());
		bb.setBusinessid(tableComboBusinessid.getText());
		bb.setDatetime(dateChooserCombo.getValue());
		bb.setEnabledate(enabledateChooserCombo.getValue());
		bb.setMoney(BigDecimal.valueOf(0));
		bb.setStaffid(comboPeople.getText());
		bb.setType("0");// 0--订单入库;1--直接入库
		bb.setUserid(SaveLogInfo.getInstance().getUsername());
		billList.add(bb);
	}

	private void addTableListener() {

		final TableEditor editor = new TableEditor(table);
		editor.horizontalAlignment = SWT.CENTER;
		editor.grabHorizontal = true;

		table.addMouseListener(new MouseAdapter() {

			private TableCombo tableComboGoodsid;
			private Text textCount;

			public void mouseDown(MouseEvent e) {

				Control oldEditor = editor.getEditor();
				if (oldEditor != null)
					oldEditor.dispose();

				Point pt = new Point(e.x, e.y);
				final TableItem item = table.getItem(pt);

				int column = -1;
				for (int i = 0; i < table.getColumnCount(); i++) {
					Rectangle rect = item.getBounds(i);
					if (rect.contains(pt)) {
						column = i;
						break;
					}
				}
				if (item != null) {
					if (column == 1 && type == 1) {
						final Composite parent = new Composite(table, SWT.NONE);
						FormLayout layout = new FormLayout();
						parent.setLayout(layout);
						FormData fd;

						tableComboGoodsid = new TableCombo(parent, SWT.BORDER
								| SWT.READ_ONLY);
						fd = new FormData();
						fd.left = new FormAttachment(0, 0);
						fd.right = new FormAttachment(100, 0);
						tableComboGoodsid.setLayoutData(fd);
						tableComboGoodsid.setForeground(item.getForeground());
						tableComboGoodsid.setText(item.getText(column));
						tableComboGoodsid.setFocus();
						tableComboGoodsid.setTableWidthPercentage(93);
						tableComboGoodsid.defineColumns(new String[] { "ID",
								"商品编号", "商品名称" });
						tableComboGoodsid.setDisplayColumnIndex(1);
						tableComboGoodsid.setShowTableHeader(true);
						if (tableComboBusinessid.getText().equals("0000"))
							goodsidList = ExtentionInfo.getInstance()
									.getGoodsInfoList();
						else {
							String businessname = textBusinessName.getText();
							int[] idObject = { 0 };
							Object[] nameObject = { businessname };
							goodsidList = (List) DbManager
									.getInstance()
									.search(
											"com.whlilong.jxc.editor.goodsInfoEditor.getBusiness",
											idObject, nameObject);
						}
						loadThreeColumnDataset(tableComboGoodsid.getTable(),
								goodsidList);
						final int col = column;
						final TableItem it = item;
						tableComboGoodsid
								.addSelectionListener(new SelectionListener() {

									@Override
									public void widgetSelected(SelectionEvent e) {
										String goodsid = tableComboGoodsid
												.getText();
										int[] idBuffer = { 0 };
										Object[] idObject = { goodsid };
										List<Goodsinfo> goodsinfo = (List) DbManager
												.getInstance()
												.search(
														"com.whlilong.jxc.editor.getGoodsInfo.getGoodsid",
														idBuffer, idObject);

										String barcode = goodsinfo.get(0)
												.getGoodshh();
										String goodsname = goodsinfo.get(0)
												.getGoodsname();
										BigDecimal originalPrice = goodsinfo
												.get(0).getCkjj();
										BigDecimal retailPrice = goodsinfo.get(
												0).getLsj();
										String unit = goodsinfo.get(0)
												.getUnit();
										int count = 0;
										double money = 0;
										double price = retailPrice
												.doubleValue();
										double discount = 1;
										if (originalPrice.doubleValue() != 0) {
											discount = price
													/ (originalPrice
															.doubleValue());
										}
										it.setText(col, goodsid);
										it.setText(2, barcode);
										it.setText(3, goodsname);
										it.setText(4, unit);
										it.setText(5, String.valueOf(count));
										it.setText(6, originalPrice.toString());
										it.setText(7, String.valueOf(discount));
										it.setText(8, retailPrice.toString());
										it.setText(9, String.valueOf(money));
										it.setText(10, retailPrice.toString());
										it.setText(11, String.valueOf(money));

										Goodsreceiving pb = (Goodsreceiving) it
												.getData();
										for (int i = 0; i < detailList.size(); i++) {
											if (detailList.get(i).getId() == pb
													.getId()) {
												detailList.get(i).setGoodsid(
														goodsid);
												detailList.get(i).setGoodsname(
														goodsname);
												detailList.get(i).setBarcode(
														barcode);
												detailList.get(i).setUnit(unit);
												detailList.get(i)
														.setOriginalprice(
																originalPrice);
												detailList
														.get(i)
														.setDiscount(
																BigDecimal
																		.valueOf(discount));
												detailList.get(i).setPrice(
														retailPrice);
												detailList.get(i)
														.setCout(count);
												detailList
														.get(i)
														.setMoney(
																BigDecimal
																		.valueOf(money));
												detailList.get(i)
														.setRetailprice(
																retailPrice);
												detailList
														.get(i)
														.setRetailmoney(
																BigDecimal
																		.valueOf(money));

												// 根据商品Id查库存表把库存数量写入detailList..

											}
										}
									}

									@Override
									public void widgetDefaultSelected(
											SelectionEvent e) {
										// TODO Auto-generated method stub

									}

								});

						parent.setBackground(tableComboGoodsid.getBackground());
						editor.setEditor(parent, item, column);
					}
					if (column == 5) {
						final Composite parent = new Composite(table, SWT.NONE);
						FormLayout layout = new FormLayout();
						parent.setLayout(layout);
						FormData fd;

						textCount = new Text(parent, SWT.BORDER);
						fd = new FormData();
						fd.left = new FormAttachment(0, 0);
						fd.right = new FormAttachment(100, 0);
						textCount.setLayoutData(fd);
						textCount.setForeground(item.getForeground());
						textCount.setText(item.getText(column));
						textCount.setFocus();
						textCount.selectAll();
						parent.setBackground(textCount.getBackground());
						editor.setEditor(parent, item, column);

						final int col = column;
						textCount.addModifyListener(new ModifyListener() {

							@Override
							public void modifyText(ModifyEvent e) {
								// TODO Auto-generated method stub
								String str = textCount.getText();
								item.setText(col, str);
								int count = Integer.valueOf(item.getText(5));
								double price = Double.valueOf(item.getText(8));
								double money = count * price;
								item.setText(9, String.valueOf(money));
								item.setText(11, String.valueOf(money));
								Goodsreceiving pb = (Goodsreceiving) item
										.getData();
								for (int i = 0; i < detailList.size(); i++) {
									if (detailList.get(i).getId() == pb.getId()) {
										detailList.get(i).setCout(count);
										detailList.get(i).setMoney(
												BigDecimal.valueOf(money));
										detailList.get(i).setRetailmoney(
												BigDecimal.valueOf(money));

										// 设置库存

									}
								}
							}
						});
						textCount.addListener(SWT.MouseExit, new Listener() {

							@Override
							public void handleEvent(Event event) {
								// TODO Auto-generated method stub
								textCount.setEditable(false);
							}

						});
						textCount.addListener(SWT.MouseDoubleClick,
								new Listener() {

									@Override
									public void handleEvent(Event event) {
										// TODO Auto-generated method stub
										textCount.setEditable(true);
									}

								});
						parent.setBackground(textCount.getBackground());
						editor.setEditor(parent, item, column);
					}
				}

				if (item.getChecked()) {
					editor.setEditor(null, item, 5);
					tableViewer.cancelEditing();// 审核过的订单不可再编辑。。。
				}

			}

		});

	}

	private void addListener() {
		tableComboBusinessid.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String id = tableComboBusinessid.getText();
				for (int i = 0; i < businessList.size(); i++) {
					if (id.equals(((Hsinfo) businessList.get(i)).getHsid())) {
						businessname = ((Hsinfo) businessList.get(i))
								.getHsname();
						break;
					}

				}

				textBusinessName.setText(businessname);
				billList.get(0).setBusinessid(tableComboBusinessid.getText());

			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub

			}

		});

		dateChooserCombo.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				// TODO Auto-generated method stub
				Calendar c = Calendar.getInstance();// 两周的有效期，当前日期加上14天。。
				c.setTime(dateChooserCombo.getValue());
				c.add(c.DATE, 14);
				enabledateChooserCombo.setValue(c.getTime());
				billList.get(0).setDatetime(dateChooserCombo.getValue());
				billList.get(0)
						.setEnabledate(enabledateChooserCombo.getValue());
			}

		});

		comboPurcharsbook.addModifyListener(new ModifyListener() {

			@Override
			public void modifyText(ModifyEvent e) {
				String bookid = comboPurcharsbook.getText();
				if (!bookid.equals("不定")) {
					int[] idbuffer = { 0 };
					Object[] idObject = { bookid };
					List<Purcharsbook> pblist = (List) DbManager
							.getInstance()
							.search(
									"com.whlilong.jxc.editor.getPurcharsBook.getBookId",
									idbuffer, idObject);
					List<Goodsreceiving> detailList = new ArrayList<Goodsreceiving>();
					Goodsreceiving checkdetail = new Goodsreceiving();
					for (int i = 0; i < pblist.size(); i++) {
						Purcharsbook pb = (Purcharsbook) pblist.get(i);
						checkdetail.setId(pb.getId());
						checkdetail.setBarcode(pb.getBarcode());
						checkdetail.setCout(pb.getCout());
						checkdetail.setDiscount(pb.getDiscount());
						checkdetail.setGoodsid(pb.getGoodsid());
						checkdetail.setGoodsname(pb.getGoodsname());
						checkdetail.setMoney(pb.getMoney());
						checkdetail.setOriginalprice(pb.getOriginalprice());
						checkdetail.setPrice(pb.getPrice());
						checkdetail.setRetailmoney(pb.getMoney());
						checkdetail.setRetailprice(pb.getPrice());
						checkdetail.setUnit(pb.getUnit());
						detailList.add(checkdetail);
					}
					tableViewer.setInput(detailList);
					type = 0;
					newFile.setEnabled(false);
				} else {
					type = 1;
					newFile.setEnabled(true);
					tableViewer.getTable().removeAll();
					detailList.clear();
				}
				billList.get(0).setBookid(comboPurcharsbook.getText());
			}

		});
		billtable.addMouseListener(new MouseAdapter() {
			public void mouseDown(MouseEvent e) {
				Point pt = new Point(e.x, e.y);
				final TableItem item = billtable.getItem(pt);
				if (item != null) {
					Inbasebill bb = (Inbasebill) item.getData();
					if (bb.getStatus().equals("1"))
						item.setChecked(true);
					else
						item.setChecked(false);

				}
			}
			public void mouseDoubleClick(MouseEvent e) {
				Point pt = new Point(e.x, e.y);
				final TableItem item = billtable.getItem(pt);
				if (item != null) {
					tabFolder.setSelection(tabItem);
					Inbasebill bb = (Inbasebill) item.getData();
					String bookid = bb.getInbaseno();
					int[] idBuffer = { 0 };
					Object[] idObject = { bookid };
					List<Goodsreceiving> pblist = (List) DbManager
							.getInstance()
							.search(
									"com.whlilong.jxc.editor.getGoodsreceiving.getInbaseno",
									idBuffer, idObject);
					setBookread(bb, pblist);

				}
			}

		});
		billtable.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				Inbasebill bb = (Inbasebill) billtable.getItem(
						billtable.getSelectionIndex()).getData();
				String inbaseno = bb.getInbaseno();
				setDetailTableInput(inbaseno);

			}

		});
	}

	protected void setBookread(Inbasebill bb, List<Goodsreceiving> pblist) {
		// TODO 设置订单录入界面（tableViewer,文本框）
		tableViewer.setInput(pblist);
		if (bb.getStatus().equals("0")){
			labelAuditingStatus.setText("未审核");
			audited=0;
		}
		else{
			labelAuditingStatus.setText("已审核");
			for (int i = 0; i < tableViewer.getTable().getItemCount(); i++) {
				tableViewer.getTable().getItem(i).setChecked(true);
			}
			audited=2;
			tableComboBusinessid.setEnabled(false);
			dateChooserCombo.setEnabled(false);
			textInbaseId.setEnabled(false);
			comboBase.setEnabled(false);
			comboPeople.setEnabled(false);
			comboPurcharsbook.setEnabled(false);
			textAuditing.setEnabled(false);
			enabledateChooserCombo.setEnabled(false);
			newFile.setEnabled(false);
		}
		tableComboBusinessid.setText(bb.getBusinessid());
		dateChooserCombo.setValue(bb.getDatetime());
		textInbaseId.setText(bb.getInbaseno());
		comboBase.setText(bb.getBaseid());
		textBase.setText("不定");
		comboPeople.setText(bb.getStaffid());
		textUser.setText(bb.getUserid());
		comboPurcharsbook.setText(bb.getBookid());
		textAuditing.setText(bb.getAuditingid());
		enabledateChooserCombo.setValue(bb.getEnabledate());
	}

	private List loadThreeColumnDataset(Table table, List comboList) {
		List rowList = new ArrayList();
		int total = (comboList == null ? 0 : comboList.size());

		for (int index = 0; index < total; index++) {
			TableItem ti = new TableItem(table, SWT.NONE);
			if (comboList.get(0) instanceof Hsinfo) {
				Hsinfo model = (Hsinfo) comboList.get(index);
				ti.setText(new String[] { String.valueOf(model.getId()),
						model.getHsid(), model.getHsname() });
				rowList.add(ti);
			}
			if (comboList.get(0) instanceof Goodsinfo) {
				Goodsinfo model = (Goodsinfo) comboList.get(index);
				ti.setText(new String[] { String.valueOf(model.getId()),
						model.getGoodsid(), model.getGoodsname() });
				rowList.add(ti);
			}
		}

		return rowList;
	}

	private void setInput() {
		List<Inbasebill> billList = null;
		try {
			billList = ExtentionInfo.getInstance().getInbaseinfo();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (billList != null && billList.size() > 0) {
			billList = getSum(billList);
			billtableViewer.setInput(billList);
			for (int i = 0; i < billList.size(); i++) {
				if (billList.get(i).getStatus().equals("1"))
					billtable.getItem(i).setChecked(true);
			}

			String detailid = billList.get(0).getInbaseno();
			setDetailTableInput(detailid);
		} else {
			billtableViewer.setInput(null);
			detailtableViewer.setInput(null);
		}

	}

	private void setDetailTableInput(String detailid) {
		int[] idBuffer = { 0 };
		Object[] idObject = { detailid };
		List detailtableList = null;
		try {
			detailtableList = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.editor.getGoodsreceiving.getInbaseno",
					idBuffer, idObject);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (detailtableList != null && detailtableList.size() > 0)
			detailtableList = getSum(detailtableList);
		detailtableViewer.setInput(detailtableList);

	}

	private List getSum(List tlist) {
		double money = 0;
		int count = 0;
		int rmoney = 0;
		if (tlist.get(0) instanceof Inbasebill) {
			List<Inbasebill> bbList = tlist;
			for (int i = 0; i < bbList.size(); i++) {
				money += bbList.get(i).getMoney().doubleValue();
			}
			Inbasebill bb = new Inbasebill();
			bb.setStatus("合计：");
			bb.setDatetime(new Date());
			bb.setEnabledate(new Date());
			bb.setMoney(BigDecimal.valueOf(money));
			bbList.add(bb);
			tlist = bbList;
		}
		if (tlist.get(0) instanceof Goodsreceiving) {
			List<Goodsreceiving> pbList = tlist;
			for (int i = 0; i < pbList.size(); i++) {
				money += pbList.get(i).getMoney().doubleValue();
				count += pbList.get(i).getCout();
				rmoney += pbList.get(i).getRetailmoney().doubleValue();

			}
			Goodsreceiving pb = new Goodsreceiving();
			pb.setGoodsid("合计：");
			pb.setMoney(BigDecimal.valueOf(money));
			pb.setCout(count);
			pb.setOriginalprice(BigDecimal.valueOf(0.0));
			pb.setDiscount(BigDecimal.valueOf(1.0));
			pb.setPrice(BigDecimal.valueOf(0.0));
			pb.setRetailprice(BigDecimal.valueOf(0.0));
			pb.setRetailmoney(BigDecimal.valueOf(rmoney));
			pbList.add(pb);
			tlist = pbList;
		}

		return tlist;
	}

	@Override
	public void addInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public void create() {
		if (!isSave && audited == 1 && type == 1) {
			Goodsreceiving ks = new Goodsreceiving();
			if (detailList.size() == 0) {
				ks.setId(1);
				ks.setGoodsid("");
				ks.setGoodsname("");
				ks.setBarcode("");
				ks.setUnit("");
				ks.setCout(Integer.valueOf(0));
				ks.setOriginalprice(BigDecimal.valueOf(0));
				ks.setDiscount(BigDecimal.valueOf(0));
				ks.setPrice(BigDecimal.valueOf(0));
				ks.setMoney(BigDecimal.valueOf(0));
				ks.setRetailprice(BigDecimal.valueOf(0));
				ks.setRetailmoney(BigDecimal.valueOf(0));
				ks.setProductdate(null);
				ks.setDisabledate(null);
				ks.setPosite("");

				tableViewer.add(ks);
				detailList.add(ks);
				int t = tableViewer.getTable().getItemCount();
				tableViewer.getTable().setSelection(t - 1);
			} else {
				int id = detailList.get(detailList.size() - 1).getId();
				if (detailList.get(detailList.size() - 1).getGoodsid().equals(
						"")) {
					// 表格中数据没有添加完整。。。

				} else {
					ks.setId(id + 1);
					ks.setGoodsid("");
					ks.setGoodsname("");
					ks.setBarcode("");
					ks.setUnit("");
					ks.setCout(Integer.valueOf(0));
					ks.setOriginalprice(BigDecimal.valueOf(0));
					ks.setDiscount(BigDecimal.valueOf(0));
					ks.setPrice(BigDecimal.valueOf(0));
					ks.setMoney(BigDecimal.valueOf(0));
					ks.setRetailprice(BigDecimal.valueOf(0));
					ks.setRetailmoney(BigDecimal.valueOf(0));
					ks.setProductdate(null);
					ks.setDisabledate(null);
					ks.setPosite("");

					tableViewer.add(ks);
					detailList.add(ks);
					int t = tableViewer.getTable().getItemCount();
					for (int i = 0; i < t; i++) {
						if (((Goodsreceiving) table.getItem(i).getData())
								.getId() == id + 1) {
							// 新添加行处于选中状态
							table.select(i);
						}
					}
				}
			}
		} else {
			initial();
			detailList.clear();
			tableViewer.getTable().removeAll();
			isSave = false;
			type = 1;
			audited = 1;
			create();
		}

	}

	@Override
	public void delete() {
		// TODO Auto-generated method stub

	}

	@Override
	public void print() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.onPrint();
	}

	@Override
	public void refresh() {
		// TODO Auto-generated method stub
		tableComboBusinessid.setEnabled(true);
		dateChooserCombo.setEnabled(true);
		textInbaseId.setEnabled(true);
		comboBase.setEnabled(true);
		comboPeople.setEnabled(true);
		comboPurcharsbook.setEnabled(true);
		textAuditing.setEnabled(true);
		enabledateChooserCombo.setEnabled(true);
		newFile.setEnabled(true);
		table.removeAll();
		
		initial();
		
		setInput();
	}

	@Override
	public void save() {
		if (isSave) {
			MessageDialog.openWarning(null, "提示", "数据已保存！");
			return;
		}

		manager.notifyListener();

		Iterator data = ((List) tableViewer.getInput()).iterator();
		if (!data.hasNext()) {
			MessageDialog.openWarning(null, "提示", "没有需要保存的数据！");
			return;
		}
		if (!MessageDialog.openConfirm(null, "提示", "准备保存数据，请确认数据已审核！")) {
			return;
		}
		Job job = new Job("正在保存数据。。。") {

			@SuppressWarnings("unchecked")
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				// TODO Auto-generated method stub

				monitor.beginTask("正在保存订单表。。。", IProgressMonitor.UNKNOWN);
				if (type == 0)
					detailList = (List) tableViewer.getInput();

				for (int j = 0; j < detailList.size(); j++) {
					Goodsreceiving pbInfo = (Goodsreceiving) detailList.get(j);
					Goodsreceiving pb = new Goodsreceiving();
					if (!pbInfo.getGoodsid().equals("")
							&& pbInfo.getGoodsid() != null) {
						pb.setBarcode(pbInfo.getBarcode());
						pb.setInbaseno(billList.get(0).getInbaseno());
						if (pbInfo.getCout() == 0) {
							audited = 0;
							row = j + 1;
							rowBuffer.append(row + " ,");
						}
						pb.setCout(pbInfo.getCout());
						pb.setDiscount(pbInfo.getDiscount());
						pb.setGoodsid(pbInfo.getGoodsid());
						pb.setGoodsname(pbInfo.getGoodsname());
						pb.setId(pbInfo.getId());
						pb.setMoney(pbInfo.getMoney());
						pb.setOriginalprice(pbInfo.getOriginalprice());
						pb.setPrice(pbInfo.getPrice());
						pb.setRetailprice(pbInfo.getRetailprice());
						pb.setRetailmoney(pbInfo.getRetailmoney());
						pb.setProductdate(pbInfo.getProductdate());
						pb.setDisabledate(pbInfo.getDisabledate());
						pb.setUnit(pbInfo.getUnit());
						pb.setPosite(pbInfo.getPosite());

						DbManager.getInstance().insert(pb);
					} else {
						return Status.CANCEL_STATUS;
					}

				}
				for (int i = 0; i < billList.size(); i++) {
					Inbasebill bb = new Inbasebill();
					Inbasebill bbList = (Inbasebill) billList.get(i);
					if (audited == 2 || audited == 1)// 判断是否有订货数量小于1的单。。
						bb.setStatus("1");
					else
						bb.setStatus("0");
					bb.setInbaseno(bbList.getInbaseno());
					bb.setAuditingid(bbList.getAuditingid());
					bb.setBaseid(bbList.getBaseid());
					bb.setBookid(bbList.getBookid());
					bb.setBusinessid(bbList.getBusinessid());
					bb.setDatetime(bbList.getDatetime());
					bb.setEnabledate(bbList.getEnabledate());
					bb.setId(bbList.getId());
					double money = 0;
					for (int k = 0; k < detailList.size(); k++) {
						money += detailList.get(k).getMoney().doubleValue();
					}
					bb.setMoney(BigDecimal.valueOf(money));
					bb.setStaffid(bbList.getStaffid());
					bb.setType(bbList.getType());
					bb.setUserid(bbList.getUserid());

					DbManager.getInstance().insert(bb);
				}

				monitor.done();
				return Status.OK_STATUS;
			}

		};
		job.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				final boolean isSuccess = event.getResult().isOK();
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						if (isSuccess) {

							MessageDialog.openInformation(null, "提示",
									"数据已经成功保存！");
							isSave = true;
							if (audited != 0)
								audited = 2;
							update();
							refresh();

						} else
							MessageDialog.openError(null, "错误",
									"编号或名称为空，数据保存失败！");
					}

				});
			}
		});
		job.setUser(false);
		job.setPriority(Job.SHORT);
		job.schedule();
	}

	private void update() {
		if (audited == 2) {
			labelAuditingStatus.setText("已审核");
			for (int i = 0; i < tableViewer.getTable().getItemCount(); i++) {
				tableViewer.getTable().getItem(i).setChecked(true);
			}
			textAuditing.setText(SaveLogInfo.getInstance().getUsername());
			writeIostorage(detailList);
			writeStorage(detailList);
		} else {
			MessageDialog.openWarning(null, "警告", "订单中第"
					+ rowBuffer.substring(0, rowBuffer.length() - 1)
					+ "行订货数量小于1，仅保存数据，不能通过审核！");
			labelAuditingStatus.setText("未审核");
			rowBuffer = new StringBuffer();
		}
		setInput();
		
	}
	
	/**
	 * 将销售信息写入库存出入库信息明细表
	 */
	private void writeIostorage(List<Goodsreceiving> dlist) {
		// TODO 写出入库信息明细表（Iostorage）
		if (dlist != null && dlist.size() > 0) {
			for (int i = 0; i < dlist.size(); i++) {
				Goodsreceiving detail = (Goodsreceiving) dlist.get(i);
				Iostorage iodetail = new Iostorage();
				iodetail.setBarcode(detail.getBarcode());
				iodetail.setCout(detail.getCout());
				iodetail.setGoodsid(detail.getGoodsid());
				iodetail.setGoodsname(detail.getGoodsname());
				iodetail.setIodate(dateChooserCombo.getValue());
				iodetail.setIostatus("1");
				iodetail.setRetailmoney(detail.getRetailmoney());
				iodetail.setStoragemoney(detail.getMoney());
				iodetail.setUnit("");
				
				DbManager.getInstance().insert(iodetail);
			}
		}
		
	}

	private void writeStorage(List<Goodsreceiving> dtlist) {
		if (dtlist != null && dtlist.size() > 0) {
			for (int i = 0; i < dtlist.size(); i++) {
				Goodsreceiving detail = (Goodsreceiving) dtlist.get(i);
				String goodsid = detail.getGoodsid();
				int[] idBuffer = { 0 };
				Object[] idObject = { goodsid };
				List<Goodsinfo> goodsinfo = (List) DbManager
						.getInstance()
						.search(
								"com.whlilong.jxc.editor.getGoodsInfo.getGoodsid",
								idBuffer, idObject);
				Storage st = new Storage();
				double inoutgap = 0;
				double storageMoney = 0;
				double retailMoney = 0;
				List<Storage> stInfo = (List) DbManager.getInstance().search(
						"com.whlilong.jxc.editor.getStorage.getgoodsid",
						idBuffer, idObject);
				if (stInfo.size() > 0) {
					Storage storage = stInfo.get(0);
					int storagecount = storage.getStoragecount();
					int count = detail.getCout();
					storagecount = storagecount+count;
					stInfo.get(0).setStoragecount(storagecount);
					double smoney = storage.getStoragemoney().doubleValue();
					double money = detail.getMoney().doubleValue();
					smoney = smoney+money;
					stInfo.get(0).setStoragemoney(BigDecimal.valueOf(smoney));
					double rmoney = storage.getSalemoney().doubleValue();
					double retailmoney = detail.getRetailmoney().doubleValue();
					rmoney = rmoney+retailmoney;
					stInfo.get(0).setSalemoney(BigDecimal.valueOf(rmoney));
					inoutgap = rmoney-smoney;
					stInfo.get(0).setInoutgap(BigDecimal.valueOf(inoutgap));
					DbManager.getInstance().update(stInfo.get(0));
					

				} else {
					st.setBarcode(detail.getBarcode());
					st.setBaseid(detail.getPosite());// 仓库号
					st.setGg(goodsinfo.get(0).getGg());
					st.setGoodsid(detail.getGoodsid());
					st.setGoodsname(detail.getGoodsname());
					st.setStoragecount(detail.getCout());
					st.setUnit(detail.getUnit());
					st.setStoragemoney(detail.getMoney());
					st.setSalemoney(detail.getRetailmoney());
					storageMoney = detail.getMoney().doubleValue();
					retailMoney = detail.getRetailmoney().doubleValue();
					inoutgap = retailMoney - storageMoney;
					st.setInoutgap(BigDecimal.valueOf(inoutgap));
					
					DbManager.getInstance().insert(st);
				}
			}
		}

	}

	@Override
	public void search() {
		// TODO Auto-generated method stub

	}

	@Override
	public void searchByCondition() {
		// TODO Auto-generated method stub

	}

	@Override
	public List getList() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void noticeFault(String message) {
		// TODO Auto-generated method stub

	}

	@Override
	public void noticeSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void preprint() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.open();
	}
}
